package com.yongbao.filter;

import cn.hutool.core.lang.UUID;
import com.yongbao.utils.ThreadMdcUtil;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * MdcFilter
 */
@Order(-2)
@Component
public class MdcFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        try {
            // 生成或获取traceId，并存入MDC
            String traceId = UUID.randomUUID().toString(true);
            MDC.put(ThreadMdcUtil.TRACE_ID, traceId);
            // 将traceId放入响应头
            response.setHeader(ThreadMdcUtil.TRACE_ID, traceId);

            chain.doFilter(request, response);
        } finally {
            // 清除MDC
            MDC.clear();
        }
    }
}
